<template>
  <div>
    <van-nav-bar
        :title="'当前词库：' + this.library"
        left-text="切换词库"
        right-text="添加单词"
        left-arrow
        @click-left="onClickLeft"
        @click-right="onClickRight"
    />
    <van-action-sheet
        v-model="optionShow"
        :actions="actions"
        cancel-text="取消"
        close-on-click-action
        @select="onSelect"
        @cancel="
const {Toast} = require('vant');
Toast('取消')"
    />
    <van-dialog v-model="areaShow" title="批量添加" show-cancel-button @confirm="allAdd" @cancel="this.addText = ''">
      <van-field
          v-model="addText"
          rows="10"
          label="输入"
          type="textarea"
          placeholder="批量输入单词，一条单词和译文为一行"
          show-word-limit
          label-width="30px"
          style="height: 100%; font-size: 16px"
      />
    </van-dialog>
    <van-dialog v-model="show" title="添加单词" show-cancel-button @confirm="add" @cancel="clean">
      <van-form >
        <van-field
            style="font-size: 16px"
            v-model="addenglish"
            name="English"
            label="English"
            placeholder="English"
            :rules="[{ required: true, message: '请填写English' }]"
        />
        <van-field
            style="font-size: 16px"
            v-model="addchinese"
            name="译文"
            label="译文"
            placeholder="译文"
            :rules="[{ required: true, message: '请填写译文' }]"
        />
      </van-form>
    </van-dialog>
    <h3 align="left" style="margin-left: 10%; margin-top: 10%">本次刷单词数量：{{ counts }}</h3>
    <div style="display: flex;align-items: center;margin-top: 5%;" >
      <span align="left" style="margin-right: 0px;margin-left: 10%; display: flex;align-items: center;font-size: 1.17em;font-weight: bold;width: 7em">
      本次学习时间：
      </span>
      <van-circle v-model="currentRateH" :rate="nowH" :speed="1.66667" :text="textH" :size="csize" style="margin-right: 5px" :color="gradientColor3" @click.native="changeColor(3)"/>：
      <van-circle v-model="currentRateM" :rate="nowM" :speed="1.66667" :text="textM" :size="csize" style="margin-right: 5px" :color="gradientColor2" @click.native="changeColor(2)"/>：
      <van-circle v-model="currentRateS" :rate="nowS" :speed="1.66667" :text="textS" :size="csize" :color="gradientColor1" @click.native="changeColor(1)"/>
      <van-dialog v-model="colorShow" :title="colorTitle" @confirm="submitColor" modal="false">
        <br/>
        0%&nbsp;&nbsp;<el-color-picker v-model="gradientColor['0%']" show-alpha></el-color-picker>
        100%&nbsp;&nbsp;<el-color-picker v-model="gradientColor['100%']" show-alpha></el-color-picker>
      </van-dialog>
    </div>

    <div align="center" style="margin-top: 15%">
      <h3>创建时间：{{ time }}</h3>
      <el-card class="box-card" :style="{width: cardWidth}" >
        <div>
        <p style="float: left">
          <el-switch
              v-model="value1"
              active-color="#13ce66"
              inactive-color="#ff4949">
          </el-switch>
          <span>&nbsp;&nbsp;English</span>
          <van-icon id="ico" style="margin-left: 10px" @click="read" name="volume-o" size="large" />
        </p><div id="mm"></div>
        </div>

        <p >
          <el-tag
              :style="{width: tagWidth}"
              :type="this.value1==true?'success':'danger'"
              effect="plain">
            {{ this.value1==true?english:'hidden' }}
          </el-tag>
        </p>
        <div>
        <p style="float: left">

            <el-switch
              v-model="value2"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          <span>&nbsp;&nbsp;中文</span>
        </p>
        </div>
        <p>
          <el-tag
              :style="{width: tagWidth}"
              :type="this.value2==true?'success':'danger'"
              effect="plain">
            {{ this.value2==true?chinese:'已隐藏' }}
          </el-tag>
        </p>
        <el-button v-show="this.value1 || this.value2" type="info" round style="margin-right: 10px" @click="kill()">记住了</el-button>
        <el-button type="success" round style="margin-left: 10px" @click="next()">下一个</el-button>
      </el-card>
    </div>
  </div>
</template>

<script>
import {Notify, Toast, Dialog} from "vant";
document.documentElement.addEventListener('touchstart', function (event) {
  if (event.touches.length > 0) {
    event.preventDefault();
  }
}, false);

var lastTouchEnd = 0;
document.documentElement.addEventListener('touchend', function (event) {
  var now = Date.now();
  if (now - lastTouchEnd <= 300) {
    event.preventDefault();
  }
  lastTouchEnd = now;
}, false);

export default {
  name: "phone",
  data(){
    return{
      colorTitle: '',
      addText: '',
      actions: [{ name: '单个添加' }, { name: '批量添加' }],
      library: localStorage.getItem("library"),
      show: false,
      optionShow: false,
      areaShow: false,
      colorShow: false,
      addenglish: '',
      addchinese: '',
      english: '',
      chinese: '',
      time: "None",
      value1: true,
      value2: true,
      cardWidth: (window.innerWidth - 20) + 'px',
      wordList:[],
      currentWord: '',
      currentIndex: 0,
      tagWidth: (window.innerWidth - 60) + 'px',
      counts: 0,
      currentRateH: 0,
      currentRateM: 0,
      currentRateS: 0,
      MM: 0,
      HH: 0,
      nowS: 100,
      nowM: 0,
      nowH: 0,
      gradientColor1: {
        '0%': 'rgba(2,253,244,0.66)',
        '100%': '#0059a0',
      },
      gradientColor2: {
        '0%': 'rgba(2,253,244,0.66)',
        '100%': '#0059a0',
      },
      gradientColor3: {
        '0%': 'rgba(2,253,244,0.66)',
        '100%': '#0059a0',
      },
      gradientColor: {
        '0%': 'rgba(2,253,244,0.66)',
        '100%': '#0059a0',
      },
      csize: '50px',
      readyList : [],
      current: 0,
      len: 0,
      changeIndex: 0,
      cloc: 0,
    }
  },
  computed: {
    textH() {
      return this.HH.toFixed(0);
    },
    textM() {
      return this.MM.toFixed(0);
    },
    textS() {
      return Math.trunc(this.currentRateS * 0.6).toFixed(0);
    },
  },
  watch:{
    currentRateS: function (){
      if(this.currentRateS == 50){
        this.nowS = 100;
      }
      if(this.currentRateS == 100){
        this.currentRateM = this.currentRateM + 1.66667
        this.MM++
        this.currentRateS = 0
        this.nowS = 50;
      }
    },
    MM:function (){
      if(this.MM == 60){
        this.MM = 0;
        this.currentRateM = 0;
        this.HH++;
        this.currentRateH += 1.66667;
      }
    }
  },
  methods: {
    submitColor(){
      let i = this.changeIndex
      if(i == 1){
        this.gradientColor1 = this.gradientColor
      }else if(i == 2){
        this.gradientColor2 = this.gradientColor
      }else if(i == 3){
        this.gradientColor3 = this.gradientColor
      }
    },
    changeColor(i){
      console.log(i)
      if(Date.now() - this.cloc <= 1000){
        this.colorShow = true
        this.changeIndex = i
        this.colorTitle = '修改 ' + (i == 1 ? '秒' : i == 2 ? '分' : '秒') + ' 的颜色'
        if(i == 1){
          this.gradientColor = this.gradientColor1
        }else if(i == 2){
          this.gradientColor = this.gradientColor2
        }else if(i == 3){
          this.gradientColor = this.gradientColor3
        }
      }else {
        this.cloc = Date.now()
      }
    },
    allAddToDB(){
      const _this = this
      setTimeout(function (){
        if(_this.current < _this.len){
          let config = {
            method: 'post',
            url: _this.$host + '/insert',
            headers: {
              'Content-Type': 'application/json'
            },
            data: _this.readyList[_this.current]
          };
          _this.$ajax(config)
              .then(function (response) {
                if(response.data === true){
                  console.log(_this.current)
                  _this.current++
                  _this.allAddToDB()
                }else{
                  _this.len = -1
                }
              })
              .catch(function (error) {
                console.log(error);
                _this.len = -1
              });
        }
      }, 100);
    },
    allAdd(){
      let textList = this.addText.split("\n")
      this.readyList = []
      let format = ''
      for(let i = 0; i < textList.length; i++){
        if(textList[i].trim() != ''){
          let param = this.onMatch(textList[i])
          if(param != null){
            this.readyList.push(param)
            format += ("english: " + param.english + "  译文: " + param.chinese + "\n");
          }
        }
      }
      this.addText = ''
      this.current = 0
      this.len = this.readyList.length
      console.log(this.current + "  " + this.len)
      const _this = this
      Dialog.confirm({
        title: '确认提交',
        message: format.trim()==''?'没有待添加单词':format,
        messageAlign: 'left'
      })
          .then(() => {
            const toast = Toast.loading({
              duration: 0, // 持续展示 toast
              forbidClick: true,
              message: '正在添加0%',
            });

            const timer = setInterval(() => {
              if (_this.current < _this.len) {
                toast.message = '正在添加 ' + Math.trunc(_this.current * 100 / _this.len) +' %';
              } else {
                clearInterval(timer);
                // 手动清除 Toast
                Toast.clear();
                if(_this.current == _this.len){
                  Toast.success({message: '添加成功 ' + _this.len + "个单词", duration: 1000});
                }else{
                  Toast.fail({message: '添加中断, 已添加前' + _this.current + "个", duration: 1000});
                }
              }
            }, 100);
            _this.allAddToDB()
          })
          .catch(() => {
          });

    },
    onMatch(text){
      let regexC = new RegExp("[\u4e00-\u9fa5]+", "g");
      let regexE = new RegExp("[a-zA-Z]+", "");
      let resultC = text.match(regexC);
      let resultE = text.match(regexE);
      if(resultC != null && resultE != null){
        let param = {
          english: resultE[0],
          chinese: resultC.join("；"),
          library: this.library
        }
        return param;
      }
      return null
    },
    onSelect(item){
      this.optionShow = false
      if(item.name == "单个添加"){
        this.show = true
      }else {
        this.areaShow = true
      }
    },
    read(){
      document.getElementById('au').play()
    },
    onClickLeft() {
      localStorage.removeItem("library")
      localStorage.removeItem("announcement")
      this.$router.replace('/')
    },
    onClickRight() {
      this.optionShow = true
    },
    add(){
      if(this.addenglish != '' && this.addchinese != ''){
        let param = {
          english: this.addenglish,
          chinese: this.addchinese,
          library: this.library
        }
        let config = {
          method: 'post',
          url: this.$host + '/insert',
          headers: {
            'Content-Type': 'application/json'
          },
          data : param
        };
        const _this = this
        this.$ajax(config)
            .then(function (response) {
              if(response.data === true){
                Toast.success({message: '添加成功!', duration: 1000});
              }else{
                Notify({ type: 'warning', message: '添加失败', duration: 500 });
              }
            })
            .catch(function (error) {
              console.log(error);
            });
      }else{
        Notify({ type: 'warning', message: '添加失败，不能有空', duration: 500 });
      }
      this.clean()
      this.show = false
    },
    getList(){
      let config = {
        method: 'post',
        url: this.$host + '/list?library=' + this.library,
        headers: { },
        data : ''
      };

      const _this = this
      this.$ajax(config)
          .then(function (response) {
            _this.wordList = response.data
            _this.getWord()
          })
          .catch(function (error) {
            console.log(error);
          });
    },
    getWord(){
      if(this.wordList.length > 0){
        this.currentIndex = Math.floor(Math.random() * this.wordList.length);
        this.currentWord = this.wordList[this.currentIndex];
      }else{
        this.currentWord = null
      }

      if(this.currentWord == null || this.currentWord === undefined){
        this.english = 'None'
        this.chinese = 'None'
        this.time = 'None'
        return
      }
      this.english = this.currentWord.english
      this.chinese = this.currentWord.chinese
      this.time = this.formatDate(new Date(this.currentWord.createTime))
      this.counts++
      let mm = document.getElementById('mm')
      mm.innerHTML = ''
      let au = document.createElement('audio')
      let scr = document.createElement('source');
      scr.type = 'audio/mpeg';
      // 传参一个回调函数名给后端，方便后端返回时执行这个在前端定义的回调函数
      scr.src = 'https://tts.youdao.com/fanyivoice?word=' + this.english + '&le=eng&keyfrom=speaker-target'
      au.className = 'au'
      au.id = 'au'
      au.appendChild(scr)
      mm.appendChild(au)
    },
    next(){
      if(this.english === 'None'){
        Notify({ type: 'warning', message: '词库里没有单词了！', duration: 500 });
        return
      }
      let config = {
        method: 'post',
        url: this.$host + '/update',
        headers: { },
        data : this.currentWord
      };

      const _this = this
      this.$ajax(config)
          .then(function (response) {
            if(response.data === true){
              _this.wordList.splice(_this.currentIndex, 1);
              if(_this.wordList.length === 0){
                _this.getList()
              }else{
                _this.getWord()
              }
            }
          })
          .catch(function (error) {
            console.log(error);
          });
    },
    kill(){
      if(this.currentWord == null || this.currentWord === undefined){
        Notify({ type: 'warning', message: '词库里没有单词了！', duration: 500 });
        return
      }
      let config = {
        method: 'post',
        url: this.$host + '/delete',
        headers: { },
        data : this.currentWord
      };

      const _this = this
      this.$ajax(config)
          .then(function (response) {
            if(response.data === true){
              _this.wordList.splice(_this.currentIndex, 1);
              if(_this.wordList.length === 0){
                _this.getList()
              }else{
                _this.getWord()
              }
            }
          })
          .catch(function (error) {
            console.log(error);
          });
    },
    formatDate(now) {
      let year = now.getFullYear(),
          month = now.getMonth() + 1,
          date = now.getDate(),
          hour = now.getHours(),
          minute = now.getMinutes(),
          second = now.getSeconds();

      return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    },
    clean(){
      this.addenglish = ''
      this.addchinese = ''
    }
  },
  created() {
    this.getList()
    let text = localStorage.getItem("announcement")
    if(text == null){
      localStorage.setItem("announcement", "1")
      Dialog.alert({
        title: '公告',
        messageAlign: 'left',
        message: '更新至 v1.5\n\n更新列表：\n1、可以进行批量添加单词，一条单词译文为一行格式要求不限，会自动提取英文和译文，如下例子：\nsuccess [成功；胜利]\n2、双击(不要点太快，慢一点)计时器的其中一个圆圈可以更改进度条颜色，暂时没有保存修改的配置\n\n本公告仅弹出一次！',
      }).then(() => {
        // on close
      });
    }
    //setTimeout(function (){document.getElementById("ico").addEventListener("click", this.read, false);}, 200);
  }
}
</script>

<style scoped>
.el-tag{
  width: 380px;
  margin-left: 0px;
  font-size: 18px;
  text-align: center;
}
.el-witch{
  float: left;
}
*{
  touch-action: none;
}
</style>